<?php
/**
 * Created by PhpStorm.
 * User: chl
 * Date: 2017/3/21 0021
 * Time: 14:36
 */
namespace app\admin\controller;
use app\models\Bases;
use think\Request;
class Product extends Base{
    public function productList(){
        $productModel = new Bases('product');
        $result['list'] = $productModel->selectData();
        return view('productList',['result'=>$result]);
    }
    public function productAdd(){
        $productModel = new Bases('product');
        try{
            if(Request()->isPost()){
                $post = input('param.');
                $validate = $this->validate($post,'Product.productAdd');
                if($validate !== true){
                    throw new \LogicException($validate,1000);
                }
                $post['duration'] = 24*3600*$post['duration'];
                $post['create_time'] = time();
                if(!($post['market_price'] > $post['discounted_price'])){
                    return self::formatResult(406,'市场价格必须大于优惠价格');
                }
                $rs = $productModel->insertData($post);
                if($rs){
                    return self::formatSuccessResult();
                }return self::formatResult(406,'操作失败');
            }

        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        return view('productAdd');
    }
    public function productSave(){
        $productModel = new Bases('product');
        try{
            $productId = intval(input('product_id'));
            $productOne= $productModel->find('product_id ='.$productId);
            $productOne['duration'] = ceil($productOne['duration']/24/3600);
            if(Request()->isPost()){
                $post = input('param.');
                $validate = $this->validate($post,'Product.productSave');
                if($validate !== true){
                    throw new \LogicException($validate,1000);
                }
                if(!($post['market_price'] > $post['discounted_price'])){
                    throw new \LogicException('市场价格必须大于优惠价格',1000);
                }
                $post['duration'] = $post['duration']*24*3600;
                $post['update_time'] = time();
                $rs = $productModel->updateData($post);
                if($rs === false){
                    throw new \LogicException('操作失败',1000);
                }

                return self::formatSuccessResult();
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        return view('productSave',['result'=>$productOne]);
    }
    public function productDelete(){
        $productId = intval(input('product_id'));
        $productModel = new Bases('product');
        $rs =$productModel->deleteDaPtaByPrimaryKey($productId);
        if($rs !== false){
            return self::formatSuccessResult();
        }return self::formatResult(406,'操作失败');
    }
}